﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Chefbook.DataAccess;
using System.ComponentModel;

namespace Chefbook.ViewModels
{
    /// <summary>
    /// View Model for the main form
    /// </summary>
    public class MainFormViewModel : ViewModelBase
    {
        ChefbookXmlRepository repository;

        /// <summary>
        /// Creates a new viewmodel for the main form with a default repository
        /// </summary>
        public MainFormViewModel():this(new ChefbookXmlRepository("recipes.xml", "categories.xml"))
        {
            
        }

        /// <summary>
        /// Creates a new viewmodel for the main form
        /// </summary>
        /// <param name="repository">The repository from which to load the data</param>
        public MainFormViewModel(ChefbookXmlRepository repository)
        {
            this.repository = repository;
            Categories = new CategoryTreeViewModel(repository.RootCategories);
            RecipeList = new RecipeListViewModel(Categories.SelectedCategory, repository);
            PreviewedRecipe = RecipeList.SelectedRecipe;
            Categories.PropertyChanged += Categories_PropertyChanged;
            RecipeList.PropertyChanged += new PropertyChangedEventHandler(RecipeList_PropertyChanged);
        }

        void RecipeList_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "SelectedRecipe")
            {
                PreviewedRecipe = RecipeList.SelectedRecipe;
            }
        }

        void Categories_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "SelectedCategory")
            {
                RecipeList.CurrentCategory = Categories.SelectedCategory;
            }
        }

        /// <summary>
        /// Gets the Treeview model of all the categories
        /// </summary>
        public CategoryTreeViewModel Categories { get; private set; }

        /// <summary>
        /// Gets the viewmodel that displays the recipes of the currently selected category
        /// </summary>
        public RecipeListViewModel RecipeList { get; private set; }

        private RecipeViewModel previewedRecipe;
        /// <summary>
        /// Gets the viewmodel of the currently previewed recipe
        /// </summary>
        public RecipeViewModel PreviewedRecipe
        {
            get { return previewedRecipe; }
            private set
            {
                if (previewedRecipe == value)
                { return; }
                previewedRecipe = value;
                OnPropertyChanged("PreviewedRecipe");
            }
        }

    }
}
